package interview.coding.string;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

import org.apache.log4j.Logger;

public class StringManipulationImpl implements StringManipulation {
	
	private static final Logger logger = Logger.getLogger(StringManipulation.class);
	
	@Override
	public char findFirstNonRepeatedChar(String s) {
		Map<Character, Boolean> charOccurrenceMap = new HashMap<Character, Boolean>();
		
		for(int i = 0; i < s.length(); i++) {
			if(charOccurrenceMap.containsKey(s.charAt(i))) {
				charOccurrenceMap.put(s.charAt(i), false);
			} else {
				charOccurrenceMap.put(s.charAt(i), true);
			}
		}
		
		for(int i = 0; i < s.length(); i++ ) {
			if(charOccurrenceMap.get(s.charAt(i))) {
				return s.charAt(i);
			}
		}
		
		return 0;
	}
	
	@Override
	public String removeString(String src, String remove) {
		Collection<Character> c = new ArrayList<Character>();
		
		for(int i = 0; i < remove.length(); i++) {
			c.add(remove.charAt(i));
		}
		
		for(Character it : c) {
			//System.out.println(it);
			logger.info(it);
		}
		
		for(int i = 0; i < src.length(); i++) {
			if(c.contains(src.charAt(i))) {
				System.out.println(src.charAt(i));
				src = src.replace(src.charAt(i), '\0');
			}
		}
		
		return src;
		
	}
	
	// have a good day -> day good a have
	public String revertString(String s) {
		String[] ss = s.split(" ");
		// use StringBuilder (for single thread only, asynchronized, thus slightly faster than StringBuffer)
		// definitely faster than ss += s since it creates a new object every time.
		
		StringBuilder sb = new StringBuilder();
		
		for(int i = ss.length - 1; i >= 0; i--) {
			sb.append(ss[i]);
			sb.append(" ");
		}
		
		return sb.toString();
	}

	// have a good day -> yad doog a evah
	@Override
	public String revertStringWord(String s) {
		Stack<Character> stack = new Stack<Character>();
		for(int i = 0; i < s.length(); i++) {
			stack.push(s.charAt(i));
		}
		
		StringBuilder sb = new StringBuilder();
		
		while(!stack.isEmpty()) {
			sb.append(stack.pop());
		}
		
		return sb.toString();
	}

}
